﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntelligentAgriculture.Domain.Entity;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Impl.Ridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    ///<summary>
    /// 种母配种服务实现
    /// </summary>
    public class BreedingInfoService : IBreedingInfoService
    {


        /// <summary>
        /// 服务接口
        /// </summary>
        private readonly IBreedingInfoRepository _breedingInfoRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<BreedingInfoService> _logger;

        /// <summary>
        /// 上下文
        /// </summary>
        private readonly AgricultureDbContext _db;

        /// 对象关系映射
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// rides
        /// </summary>

        private readonly CSRedis.CSRedisClient _client;

        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IridegRepository _iridegRepository;

        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IColumnManRepository _columnManRepository;

        /// <summary>
        /// 羊只档案仓储
        /// </summary>

        private readonly ISheepFileModelRepository _sheepFileModelRepository;

        /// <summary>
        /// 历史记录
        /// </summary>
        private readonly IHistoryRecordRepository _historyRecordRepository;


        /// <summary>
        /// 羊只转舍
        /// </summary>
        private readonly ISheepRescissionRepository _sheepRescissionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="breedingInfoRepository">服务接口</param>
        public BreedingInfoService(IBreedingInfoRepository breedingInfoRepository, AgricultureDbContext db, IMapper mapper, ILogger<BreedingInfoService> logger,IridegRepository iridegRepository, IColumnManRepository columnManRepository, ISheepFileModelRepository sheepFileModelRepository, IHistoryRecordRepository historyRecordRepository,ISheepRescissionRepository sheepRescissionRepository)
        {
            _breedingInfoRepository = breedingInfoRepository;
            _db = db;
            _mapper = mapper;
            _logger = logger;
            _client = new CSRedis.CSRedisClient("127.0.0.1:6379");
            _columnManRepository = columnManRepository;
            _iridegRepository = iridegRepository;
            _sheepFileModelRepository = sheepFileModelRepository;
            _historyRecordRepository = historyRecordRepository;
            _sheepRescissionRepository = sheepRescissionRepository;

        }
        /// <summary>
        /// 种母配种显示
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns><返回数据/returns>
        public async Task<PageOutput<BreedingInfoOutPut>> GetBreedingInfoAsync(BreedingInfoInput? input)
        {
            try
            {
               
                //从redis获取数据
                var breedinginfos = _client.Get<List<Breedinginfo>>("getBreedingInfo");
                if (breedinginfos == null)
                {
                    //如果没有，则从数据库获取数据
                    breedinginfos = _db.Breedinginfos.Where(c => c.Isdel == false).ToList();
                    // 将数据存入Redis，缓存时间待定，例如设置有效期为30分钟
                    _client.Set("getBreedingInfo", breedinginfos, TimeSpan.FromMinutes(30));
                }
                _logger.LogInformation("这是显示种母配种表");


                var list = await _breedingInfoRepository.GetBreedinginfoAsync();
                //栋舍
                var rideg = _iridegRepository.Showinfo();
                //栏位
                var column = _columnManRepository.GetShow();
                //档案
                var sheepfilr = await _sheepFileModelRepository.GetSheepfilemodels();
                

                var filteredList = (from breedinginfo in list
                                    join ridgepole in rideg on breedinginfo.ToBuildingManageId equals                ridgepole.RidgepoleId
                                    join columns in column on breedinginfo.ToColumMangementId equals columns.ColumnManagementId
                                    select new BreedingInfoOutPut
                                    {
                                         ToColumMangementId= ridgepole.RidgepoleId,
                                         ToBuildingManageId= columns.ColumnManagementId,
                                         ToBulidName=rideg.FirstOrDefault(c=>c.RidgepoleId==breedinginfo.ToBuildingManageId).RidgepoleName,

                                         ToColumName=column.FirstOrDefault(c=>c.ColumnManagementId==breedinginfo.ToColumMangementId).ColumnName,


                                         BreedDate =breedinginfo.BreedDate,
                                         BreedId=breedinginfo.BreedId,
                                         BreedState=breedinginfo.BreedState,
                                         BreedStyle=breedinginfo.BreedStyle,
                                         CreateName=breedinginfo.CreateName,
                                         CreateTime=breedinginfo.CreateTime,

                                         CurrentBuilding=breedinginfo.CurrentBuilding,
                                        CurrentBuildName = rideg.FirstOrDefault(c => c.RidgepoleId == breedinginfo.CurrentBuilding).RidgepoleName,


                                        CurrentField =breedinginfo.CurrentField,
                                        CurrentColumName=column.FirstOrDefault(c=>c.ColumnManagementId==breedinginfo.CurrentField).ColumnName,




                                         DocumentNumber=breedinginfo.DocumentNumber,
                                         EarTag=breedinginfo.EarTag,
                                         EventDate=breedinginfo.EventDate,
                                         FirstMatingRam=breedinginfo.FirstMatingRam,
                                         FirstScore=breedinginfo.FirstScore,
                                         Isdel=breedinginfo.Isdel,
                                         //LastBreedDate= list.FirstOrDefault(c => c.LastBreedDate == breedinginfo.LastBreedDate).BreedDate,
                                         LastBreedDate=breedinginfo.LastBreedDate,
                                         MaleBreed = sheepfilr.FirstOrDefault(c => c.EarTag == breedinginfo.FirstMatingRam).Variety,
                                        MotherVariety = sheepfilr.FirstOrDefault(c=>c.EarTag== breedinginfo.EarTag).Variety,
                                         OestrusType =breedinginfo.OestrusType,
                                         UpdateName=breedinginfo.UpdateName,
                                         UpdateTime=breedinginfo.UpdateTime,
                                         UserId=breedinginfo.UserId,
                                    }).ToList();

                // 应用额外的筛选条件
                if (!string.IsNullOrEmpty(input.EarTag))
                {
                    filteredList = filteredList.Where(c => c.EarTag.Contains(input.EarTag)).ToList();
                }
                if (!string.IsNullOrEmpty(input.Sdate))
                {
                    var startDate = DateTime.Parse(input.Sdate);
                    filteredList = filteredList.Where(c => c.BreedDate >= startDate).ToList();
                }
                if (!string.IsNullOrEmpty(input.Edate))
                {
                    var endDate = DateTime.Parse(input.Edate).AddDays(1);
                    filteredList = filteredList.Where(c => c.BreedDate < endDate).ToList();
                }
                if (input.UserId>0)
                {
                    filteredList=filteredList.Where(c=>c.UserId==input.UserId).ToList();
                }

                // 分页处理
                var pagedData = filteredList.OrderByDescending(c => c.BreedId)
                                            .Skip((input.PageIndex - 1) * input.PageSize)
                                            .Take(input.PageSize)
                                            .ToList();

                var result = new PageOutput<BreedingInfoOutPut>
                {
                    TotalCount = filteredList.Count(), // 计算筛选后的总条数
                    PageSize = input.PageSize,
                    Data = _mapper.Map<List<BreedingInfoOutPut>>(pagedData)
                };



                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("显示种母配种发生异常：" + ex.Message);
                throw;
            }
        }




        /// <summary>
        /// 逻辑删除种母配种表
        /// </summary>
        /// <param name="breedId">主键id</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> DeleteBreedingInfo(int breedId)
        {
            return await _breedingInfoRepository.DeleteBreedingInfo(breedId);
        }

        /// <summary>
        /// 批量逻辑删除种母配种表
        /// </summary>
        /// <param name="breedIds">id</param>
        /// <returns>返回数据</returns>
        public async Task<int> DeleteRangeBreedingInfo(IEnumerable<int> breedIds)
        {
            return await _breedingInfoRepository.DeleteRangeBreedingInfo(breedIds);
        }




        /// <summary>
        /// 批量添加种母配种数据
        /// </summary>
        /// <param name="inputs">实体列表</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddBreedinginfoAsync(List<Breedinginfo> inputs)
        {
            //档案
            var sheepfilr = await _sheepFileModelRepository.GetSheepfilemodels();
           
            //种母历史记录
            var history = await _historyRecordRepository.GetHistoryRecordsAsync();
         
            // 为每个输入项设置创建相关的属性
            foreach (var input in inputs)
            {
                input.CreateTime = DateTime.Now;
                input.CreateName = "牛骞若";
                input.DocumentNumber = YitIdHelper.NextId().ToString();
                input.BreedDate = DateTime.Now;
                input.UpdateTime = DateTime.Now;
                input.UpdateName = "赵思彤";
                input.UserId = 1;
                input.Isdel = false;
                input.MotherVariety = sheepfilr.FirstOrDefault(c => c.EarTag == input.EarTag).Variety;
                input.MaleBreed= sheepfilr.FirstOrDefault(c => c.EarTag == input.FirstMatingRam).Variety;

                // 获取上一次配种时间
                var historyEntry = history.FirstOrDefault(c => c.EarTag == input.EarTag);

                if (historyEntry != null)
                {
                    input.LastBreedDate = historyEntry.BreedDate;
                }
                else
                {
                    input.LastBreedDate = input.BreedDate; // 默认使用当前的 BreedDate，或根据需要进行处理
                }

             
            }

            // 批量添加种母配种表数据
            await _breedingInfoRepository.AddBreedinginfoAsync(inputs);

            // 处理与羊只档案的关联和更新
            foreach (var input in inputs)
            {
                var sheep = await _sheepFileModelRepository.GetSheepfilemodels();
                var sheeplist = sheep.FirstOrDefault(c => c.EarTag == input.EarTag);

                if (sheeplist != null)
                {
                    // 更新羊只档案数据
                    sheeplist.BuildingId = input.ToBuildingManageId;
                    sheeplist.ColumnId = input.ToColumMangementId;
                    sheeplist.ReproductionState = input.BreedState;

                    // 保存更新后的羊只档案数据
                    await _sheepFileModelRepository.UpdaSheepFileModel(sheeplist);
                }
            }

            //处理种母历史记录
            var historylist = inputs.Select(c => new Historyrecord
            {
                 EarTag = c.EarTag,
                 BreedDate = c.BreedDate,
                 BreedingRaw=c.FirstMatingRam,
                 CreateName = c.CreateName,
                 CreateTime = c.CreateTime, 
                 CurrentPregnancy=1,
                 DeliveryDate=DateTime.Now,
                 FreaksNumber=null,
                 HealthyNumber=null,
                 HealthyTotalWeight=null,
                 Isdel=false,
                 LambNumber=null,
                 MalformationNumber=null,
                 MummyNumber    =null,
                 PregnancyDate  =DateTime.Now,
                 PregnancyResult=null,
                 StillbirthNumber=null,
                 UpdateName=c.UpdateName,
                UpdateTime=c.UpdateTime,
                 WeaningCount=null,
                 WeaningDate = DateTime.Now,
                 WeaningWeight=null,

            }).ToList();
            await _historyRecordRepository.AddHistoryrecordAsync(historylist);
            //处理羊只转舍
            var rescission = inputs.Select(c => new Sheeprescission
            {
                EarTag = c.EarTag,
                CreateName = c.CreateName,
                DocumentNumber = YitIdHelper.NextId().ToString(),
                CreateTime=DateTime.Now,
                Isdel = false,
                OutBuildingManageId=c.CurrentBuilding,
                OutColumMangementId=c.CurrentField,
                RoundType=1,
                SheepRescissionDate=DateTime.Now,
                SheepRescissionSex=sheepfilr.FirstOrDefault(item=>item.EarTag==c.EarTag).SheepSex,
                SheepType=2,
                ToBuildingManageId=c.ToBuildingManageId,
                ToColumMangementId=c.ToColumMangementId,
                UpdateName=c.UpdateName,
               UpdateTime=DateTime.Now,
               Variety = sheepfilr.FirstOrDefault(item=>item.EarTag==c.EarTag).Variety,
              

            }).ToList();
            await _sheepRescissionRepository.AddSheepRescission(rescission);

          

            return inputs.Count;
        }








    }
}
